/**
 * 作者:hzq
 * 文件说明:
 * Creeated by hzq on 2018/7/5
 *
 */
import Cookies from 'js-cookie';

const storage = {
    prefix: 'phone',
    getSessionStorage(params) {
        return sessionStorage.getItem(storage.prefix + '_' + params);
    },
    getLocalStorage(params) {
        return localStorage.getItem(storage.prefix + '_' + params);
    },
    getCookies(params) {
        return Cookies.get(storage.prefix + '_' + params);
    },
    saveSessionStorage(data) {
        for (let key in data) {
            sessionStorage.setItem(storage.prefix + '_' + key, data[key]);
        }
    },
    saveLocalStorage(data) {
        for (let key in data) {
            localStorage.setItem(storage.prefix + '_' + key, data[key]);
        }
    },
    saveCookies(data) {
        for (let key in data) {
            Cookies.set(storage.prefix + '_' + key, data[key]);
        }
    },
    saveAll(prefix) {
        storage.prefix = prefix;
        handleCookies();
        handleStorage('localStorage');
        handleStorage('sessionStorage');
    },
    delSessionStorage(params) {
        sessionStorage.removeItem(storage.prefix + '_' + params);
    },
    delLocalStorage(params) {
        localStorage.removeItem(storage.prefix + '_' + params);
    },
    delCookies(params) {
        Cookies.remove(storage.prefix + '_' + params);
    },
    delAll() {
        window.sessionStorage.clear();
        window.localStorage.clear();
        for (let key in Cookies.get()) Cookies.remove(key);
    }
};
const handleCookies = () => {
    let data = JSON.parse(JSON.stringify(Cookies.get()));
    for (let key in data) {
        Cookies.remove(key);
        Cookies.set(storage.prefix + '_' + key, data[key]);
    }
};
const handleStorage = flag => {
    let data = JSON.parse(JSON.stringify(window[flag]));
    window[flag].clear();
    for (let key in data) {
        window[flag].setItem(storage.prefix + '_' + key, data[key]);
    }
};
const install = Vue => {
    if (install.installed) return;
    install.installed = true;
    Object.defineProperties(Vue.prototype, {
        storage: {
            get() {
                return storage;
            }
        }
    });
    Vue.storage = storage;
};
export default { install };
